<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button
            type="primary"
            icon="el-icon-plus"
            @click="addDialogVisible = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="id" label="ID"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="mobile" label="电话号码"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="拥有的角色"
          ><template slot-scope="scope">
            <el-tag
              type="success"
              v-for="(item, index) in scope.row.roleArr"
              :key="index"
              >{{ item }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="last_login_ip" label="上次登录的IP">
        </el-table-column>
        <el-table-column prop="last_login_time" label="上次登录的时间">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUser(scope.row.id)"
              >删除</el-button
            >
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-setting"
                size="mini"
                @click="showSettingDialog(scope.row.id)"
                >设置</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑管理员"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配角色"
      :visible.sync="settingDialogVisible"
      width="40%"
    >
      <el-transfer
        v-model="roleIds"
        :data="roleList"
        :props="{
          key: 'id',
          label: 'name',
        }"
        :titles="['未拥有的角色', '已拥有的角色']"
        @change="assignRoleToUser"
      ></el-transfer>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    //验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    //验证手机规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      roleList: [],
      roleIds: [],
      userList: [],
      toUid: 0,
      total: 0,
      page: 1,
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 20
      },
      addDialogVisible: false,
      editDialogVisible: false,
      settingDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            messgae: '用户名的长度在3到10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            messgae: '密码长度在5到15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('api/admin/users', {
        params: this.queryInfo
      })
      // if (res.errno !== 0) return this.$message.error('获取用户列表失败')
      this.userList = res.list
      this.total = res.total
      this.queryInfo.pageNum = res.page
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    async userStateChanged (row) {
      const { data: res } = await this.$http.put('api/admin/state', {
        state: row.state
      })
      if (res.errno !== 0) {
        row.state = !row.state
        return (this.$message.error = res.errmsg)
      }
      this.$message.success('更新成功')
    },
    //监听点击添加用户对话框
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    //添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'api/admin/save',
          this.addForm
        )
        if (res.errno !== 0) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    //展示编辑用户对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(
        'api/admin_user/view?userId=' + id
      )
      if (res.errno !== 0) {
        this.$message.error('获取数据失败')
      }

      this.editForm = res.data

      this.editDialogVisible = true
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'api/admin/edit',
          this.editForm
        )

        if (res.errno !== 0) {
          return this.$message.error('修改用户失败')
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('修改用户成功')
      })
    },
    async delUser (id) {
      const res = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (res !== 'confirm') {
        return this.$message.info('取消删除操作')
      }
      const { data: res2 } = await this.$http.delete('api/admin/del?id=' + id)
      if (res2.errno !== 0) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    //设置页面
    showSettingDialog (id) {
      this.settingDialogVisible = true
      this.getRoleList(id)
    },
    //获取角色列表
    async getRoleList (id) {
      const { data: res } = await this.$http.get(
        'api/admin_user/roles?id=' + id
      )
      if (res.errno !== 0) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data.all
      this.roleIds = res.data.own
      this.toUid = id
    },
    //分配角色给用户
    async assignRoleToUser (value) {
      let roles = ''
      if (value) {
        roles = value.join(',')
      }
      const postData = { toUid: this.toUid, roles: roles }
      const { data: res } = await this.$http.post(
        'api/admin_user/roles',
        postData
      )
      if (res.errno !== 0) {
        return this.$message.error('分配角色失败')
      }
      return this.$message.success('分配角色成功')
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin-top: 5px;
}
</style>
